// 游戏状态
const gameState = {
    isReading: false,
    isRecording: false,
    startTime: null,
    currentTime: 0,
    effectiveTime: 0,
    streakDays: 0,
    lastPlayDate: null,
    treeStage: 0,
    treeStages: [
        { name: "种子", threshold: 0, image: "assets/tree-stages/seed.png" },
        { name: "幼苗", threshold: 10 * 60, image: "assets/tree-stages/sprout.png" },
        { name: "小树", threshold: 30 * 60, image: "assets/tree-stages/sapling.png" },
        { name: "大树", threshold: 90 * 60, image: "assets/tree-stages/tree.png" },
        { name: "开花", threshold: 180 * 60, image: "assets/tree-stages/bloom.png" },
        { name: "结果", threshold: 360 * 60, image: "assets/tree-stages/fruit.png" }
    ],
    settings: {
        volumeThreshold: 50,
        dailyGoal: 30 * 60,
        autoRecord: true
    },
    recordings: [],
    achievements: [
        { id: "first5", name: "初次朗读", desc: "首次朗读超过5分钟", threshold: 5 * 60, unlocked: false },
        { id: "daily", name: "每日目标", desc: "完成每日朗读目标", threshold: 30 * 60, unlocked: false },
        { id: "streak3", name: "三日连胜", desc: "连续3天完成朗读", threshold: 3, unlocked: false },
        { id: "record5", name: "小小录音师", desc: "保存5次朗读录音", threshold: 5, unlocked: false }
    ],
    mediaRecorder: null,
    audioChunks: []
};

// DOM元素
const elements = {
    treeImage: document.getElementById("tree-image"),
    timer: document.getElementById("timer"),
    streak: document.getElementById("streak"),
    startBtn: document.getElementById("start-btn"),
    progressFill: document.getElementById("progress-fill"),
    progressText: document.getElementById("progress-text"),
    volumeBar: document.getElementById("volume-bar"),
    volumeValue: document.getElementById("volume-value"),
    particlesContainer: document.getElementById("particles-container"),
    achievementPopup: document.getElementById("achievement-popup"),
    achievementDesc: document.getElementById("achievement-desc"),
    settingsBtn: document.getElementById("settings-btn"),
    settingsPanel: document.getElementById("settings-panel"),
    volumeThreshold: document.getElementById("volume-threshold"),
    thresholdValue: document.getElementById("threshold-value"),
    dailyGoal: document.getElementById("daily-goal"),
    saveSettings: document.getElementById("save-settings"),
    autoRecord: document.getElementById("auto-record"),
    historyBtn: document.getElementById("history-btn"),
    historyPanel: document.getElementById("history-panel"),
    historyList: document.getElementById("history-list"),
    historyFilter: document.getElementById("history-filter"),
    deleteAllBtn: document.getElementById("delete-all-btn"),
    audioPlayer: document.getElementById("audio-player"),
    recordingPopup: document.getElementById("recording-popup"),
    recordingDuration: document.getElementById("recording-duration"),
    saveRecording: document.getElementById("save-recording"),
    discardRecording: document.getElementById("discard-recording"),
    playRecording: document.getElementById("play-recording"),
    closePanelBtn: document.querySelector(".btn-close-panel")
};

// 音频分析器
let audioContext, analyser, microphone;

// 初始化游戏
function initGame() {
    loadGameData();
    updateUI();
    setupEventListeners();
    checkStreak();
    renderHistoryList();

    // 预加载音频上下文
    try {
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        analyser = audioContext.createAnalyser();
        analyser.fftSize = 32;
        
    } catch (e) {
        console.warn("音频API不支持:", e);
    }
}

// 加载游戏数据
function loadGameData() {
    const savedData = localStorage.getItem("readingTreeGame");
    if (savedData) {
        const data = JSON.parse(savedData);

        // 合并数据但要保留默认设置
        const defaultSettings = {...gameState.settings};
        Object.assign(gameState, data);
        gameState.settings = {...defaultSettings, ...data.settings};
    }

    // 应用设置
    elements.volumeThreshold.value = gameState.settings.volumeThreshold;
    elements.thresholdValue.textContent = gameState.settings.volumeThreshold;
    elements.dailyGoal.value = gameState.settings.dailyGoal / 60;
    elements.autoRecord.checked = gameState.settings.autoRecord;
}

// 保存游戏数据
function saveGameData() {
    // 不保存音频数据到本地存储
    const saveData = {
        ...gameState,
        mediaRecorder: null,
        audioChunks: []
    };
    localStorage.setItem("readingTreeGame", JSON.stringify(saveData));
}

// 设置事件监听
function setupEventListeners() {
    elements.startBtn.addEventListener("click", toggleReading);
    document.querySelector(".btn-close").addEventListener("click", () => {
        elements.achievementPopup.classList.add("hidden");
    });

    // 设置面板
    elements.settingsBtn.addEventListener("click", toggleSettingsPanel);
    elements.volumeThreshold.addEventListener("input", () => {
        elements.thresholdValue.textContent = elements.volumeThreshold.value;
    });
    elements.saveSettings.addEventListener("click", saveSettings);

    // 历史记录面板
    elements.historyBtn.addEventListener("click", toggleHistoryPanel);
    elements.closePanelBtn.addEventListener("click", () => {
        elements.historyPanel.classList.add("hidden");
    });
    elements.historyFilter.addEventListener("change", renderHistoryList);
    elements.deleteAllBtn.addEventListener("click", confirmDeleteAll);

    // 录音弹窗
    elements.saveRecording.addEventListener("click", saveCurrentRecording);
    elements.discardRecording.addEventListener("click", discardCurrentRecording);
    elements.playRecording.addEventListener("click", playCurrentRecording);

    // 事件委托
    elements.historyList.addEventListener("click", (e) => {
        if (e.target.classList.contains("btn-play")) {
            playRecording(e.target.dataset.id);
        } else if (e.target.classList.contains("btn-delete")) {
            confirmDeleteRecording(e.target.dataset.id);
        }
    });
}

// 切换设置面板
function toggleSettingsPanel() {
    elements.settingsPanel.classList.toggle("hidden");
    if (!elements.settingsPanel.classList.contains("hidden")) {
        elements.historyPanel.classList.add("hidden");
    }
}

// 切换历史面板
function toggleHistoryPanel() {
    elements.historyPanel.classList.toggle("hidden");
    if (!elements.historyPanel.classList.contains("hidden")) {
        elements.settingsPanel.classList.add("hidden");
        renderHistoryList();
    }
}

// 保存设置
function saveSettings() {
    gameState.settings.volumeThreshold = parseInt(elements.volumeThreshold.value);
    gameState.settings.dailyGoal = parseInt(elements.dailyGoal.value) * 60;
    gameState.settings.autoRecord = elements.autoRecord.checked;
    elements.settingsPanel.classList.add("hidden");
    saveGameData();
    showToast("设置已保存");
}

// 检查连续打卡
function checkStreak() {
    const today = new Date().toDateString();
    if (gameState.lastPlayDate) {
        const lastDate = new Date(gameState.lastPlayDate);
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);

        if (lastDate.toDateString() === yesterday.toDateString()) {
            gameState.streakDays++;
        } else if (lastDate.toDateString() !== today) {
            gameState.streakDays = 0;
        }
    }

    updateStreakUI();
}

// 更新UI
function updateUI() {
    // 更新树状态
    updateTreeStage();

    // 更新进度条
    const progress = Math.min(gameState.effectiveTime / gameState.settings.dailyGoal * 100, 100);
    elements.progressFill.style.width = `${progress}%`;
    elements.progressText.textContent = `${Math.round(progress)}%`;

    // 更新计时器
    updateTimerUI();
}

// 更新树阶段
function updateTreeStage() {
    for (let i = gameState.treeStages.length - 1; i >= 0; i--) {
        if (gameState.effectiveTime >= gameState.treeStages[i].threshold) {
            if (gameState.treeStage !== i) {
                gameState.treeStage = i;
                elements.treeImage.src = gameState.treeStages[i].image;

                // 升级效果
                if (i > 0) {
                    animateTreeUpgrade();
                }
            }
            break;
        }
    }
}

// 树升级动画
function animateTreeUpgrade() {
    elements.treeImage.style.transform = "scale(1.1)";
    setTimeout(() => {
        elements.treeImage.style.transform = "scale(1)";
    }, 300);

    // 升级粒子效果
    createParticles(30, true);
}

// 更新计时器UI
function updateTimerUI() {
    const totalSeconds = gameState.currentTime;
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    elements.timer.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// 更新连续打卡UI
function updateStreakUI() {
    elements.streak.textContent = `🔥 连续打卡: ${gameState.streakDays}天`;
}

// 切换朗读状态
function toggleReading() {
    if (gameState.isReading) {
        stopReading();
    } else {
        startReading();
    }
}

// 开始朗读
async function startReading() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: false
            }
        });

        if (!audioContext) {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
            analyser = audioContext.createAnalyser();
        }

        microphone = audioContext.createMediaStreamSource(stream);
        microphone.connect(analyser);

        // 开始录音
        if (gameState.settings.autoRecord) {
            startRecording(stream);
        }

        gameState.isReading = true;
        gameState.startTime = Date.now();
        elements.startBtn.textContent = "停止朗读";

        // 开始动画循环
        requestAnimationFrame(updateAudioAnalysis);

        // 开始计时器
        gameState.timerInterval = setInterval(updateTimer, 1000);

        showToast("朗读已开始");
    } catch (error) {
        console.error("无法访问麦克风:", error);
        showToast("需要麦克风权限才能开始朗读", 3000);
    }
}

// 开始录音
function startRecording(stream) {
    gameState.mediaRecorder = new MediaRecorder(stream);
    gameState.audioChunks = [];

    gameState.mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
            gameState.audioChunks.push(event.data);
        }
    };

    gameState.mediaRecorder.onstop = () => {
        const audioBlob = new Blob(gameState.audioChunks, { type: 'audio/wav' });
        gameState.currentRecording = {
            blob: audioBlob,
            duration: gameState.currentTime,
            timestamp: new Date().toISOString()
        };

        if (gameState.settings.autoRecord) {
            saveCurrentRecording();
        } else {
            showRecordingPopup();
        }
    };

    gameState.mediaRecorder.start();
    gameState.isRecording = true;
}

// 显示录音完成弹窗
function showRecordingPopup() {
    elements.recordingDuration.textContent = formatTime(gameState.currentRecording.duration);
    elements.recordingPopup.classList.remove("hidden");
}

// 保存当前录音
function saveCurrentRecording() {
    if (!gameState.currentRecording) return;

    // 创建对象URL
    const audioUrl = URL.createObjectURL(gameState.currentRecording.blob);

    // 添加到历史记录
    gameState.recordings.unshift({
        id: Date.now().toString(),
        url: audioUrl,
        duration: gameState.currentRecording.duration,
        timestamp: gameState.currentRecording.timestamp
    });

    // 保存数据
    saveGameData();
    renderHistoryList();

    // 检查成就
    checkRecordingAchievements();

    // 关闭弹窗
    elements.recordingPopup.classList.add("hidden");
    showToast("录音已保存");

    // 清理
    gameState.currentRecording = null;
}

// 丢弃当前录音
function discardCurrentRecording() {
    if (gameState.currentRecording) {
        URL.revokeObjectURL(gameState.currentRecording.url);
        gameState.currentRecording = null;
        elements.recordingPopup.classList.add("hidden");
        showToast("录音已丢弃");
    }
}

// 播放当前录音
function playCurrentRecording() {
    if (!gameState.currentRecording) return;

    const audioUrl = URL.createObjectURL(gameState.currentRecording.blob);
    elements.audioPlayer.src = audioUrl;
    elements.audioPlayer.classList.remove("hidden");
    elements.audioPlayer.play();
}

// 检查录音相关成就
function checkRecordingAchievements() {
    // 检查录音次数成就
    const recordCount = gameState.recordings.length;
    const recordAchievement = gameState.achievements.find(a => a.id === "record5");

    if (!recordAchievement.unlocked && recordCount >= recordAchievement.threshold) {
        recordAchievement.unlocked = true;
        showAchievement(recordAchievement);
    }
}

// 停止朗读
function stopReading() {
    gameState.isReading = false;

    // 断开麦克风
    if (microphone) {
        microphone.disconnect();
    }

    // 停止录音
    if (gameState.isRecording && gameState.mediaRecorder) {
        gameState.mediaRecorder.stop();
        gameState.isRecording = false;
    }

    // 停止计时器
    clearInterval(gameState.timerInterval);

    // 更新最后播放日期
    const today = new Date();
    gameState.lastPlayDate = today.toISOString();

    // 检查是否是新的一天
    if (!localStorage.getItem("lastPlayDate") ||
        new Date(localStorage.getItem("lastPlayDate")).toDateString() !== today.toDateString()) {
        gameState.streakDays++;
        localStorage.setItem("lastPlayDate", today.toISOString());
        updateStreakUI();
    }

    elements.startBtn.textContent = "开始朗读";
    saveGameData();
}

// 音频分析
function updateAudioAnalysis() {
    if (!gameState.isReading) return;

    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);
    analyser.getByteFrequencyData(dataArray);

    // 计算平均音量
    let sum = 0;
    for (let i = 0; i < bufferLength; i++) {
        sum += dataArray[i];
    }
    const average = sum / bufferLength;
    const dbValue = Math.round(average / 255 * 100); // 转换为0-100dB范围

    // 更新音量UI
    elements.volumeBar.style.width = `${dbValue}%`;
    elements.volumeValue.textContent = dbValue;

    // 检查是否有效朗读
    if (dbValue > gameState.settings.volumeThreshold) {
        gameState.effectiveTime++;
        updateUI();

        // 创建粒子效果
        if (Math.random() < 0.1) {
            createParticles(1);
        }

        // 检查成就
        checkAchievements();
    }

    // 继续动画循环
    requestAnimationFrame(updateAudioAnalysis);
}

// 创建粒子效果
function createParticles(count, isSpecial = false) {
    for (let i = 0; i < count; i++) {
        const particle = document.createElement("div");
        particle.className = "particle";

        // 随机选择粒子图像
        const imgIndex = isSpecial ? 2 : Math.floor(Math.random() * 2);
        particle.style.backgroundImage = `url(assets/particles/leaf${imgIndex + 1}.png)`;

        // 随机位置和大小
        const size = isSpecial ?
            Math.random() * 30 + 20 :
            Math.random() * 20 + 10;

        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        particle.style.left = `${Math.random() * 100}%`;
        particle.style.top = `${Math.random() * 100}%`;

        // 随机动画延迟和持续时间
        const delay = Math.random() * 2;
        const duration = 3 + Math.random() * 2;
        particle.style.animationDelay = `${delay}s`;
        particle.style.animationDuration = `${duration}s`;

        elements.particlesContainer.appendChild(particle);

        // 自动移除
        setTimeout(() => {
            particle.remove();
        }, (duration + delay) * 1000);
    }
}

// 检查成就
function checkAchievements() {
    gameState.achievements.forEach(achievement => {
        if (!achievement.unlocked) {
            let conditionMet = false;

            switch (achievement.id) {
                case "first5":
                    conditionMet = gameState.effectiveTime >= achievement.threshold;
                    break;
                case "daily":
                    conditionMet = gameState.effectiveTime >= gameState.settings.dailyGoal;
                    break;
                case "streak3":
                    conditionMet = gameState.streakDays >= achievement.threshold;
                    break;
            }

            if (conditionMet) {
                achievement.unlocked = true;
                showAchievement(achievement);
            }
        }
    });
}

// 显示成就
function showAchievement(achievement) {
    elements.achievementDesc.textContent = achievement.desc;
    elements.achievementPopup.classList.remove("hidden");

    // 3秒后自动隐藏
    setTimeout(() => {
        if (!elements.achievementPopup.classList.contains("hidden")) {
            elements.achievementPopup.classList.add("hidden");
        }
    }, 3000);
}

// 渲染历史记录列表
function renderHistoryList() {
    const filter = elements.historyFilter.value;
    const now = new Date();
    let filteredRecordings = [...gameState.recordings];

    // 应用筛选
    if (filter !== "all") {
        filteredRecordings = filteredRecordings.filter(recording => {
            const recordDate = new Date(recording.timestamp);

            switch (filter) {
                case "today":
                    return recordDate.toDateString() === now.toDateString();
                case "week":
                    const weekStart = new Date(now);
                    weekStart.setDate(now.getDate() - now.getDay());
                    return recordDate >= weekStart;
                case "month":
                    return recordDate.getMonth() === now.getMonth() &&
                        recordDate.getFullYear() === now.getFullYear();
                default:
                    return true;
            }
        });
    }

    // 渲染列表
    elements.historyList.innerHTML = filteredRecordings.length > 0 ?
        filteredRecordings.map(recording => `
            <div class="history-item" data-id="${recording.id}">
                <div class="history-info">
                    <div class="history-date">${formatDate(recording.timestamp)}</div>
                    <div class="history-duration">${formatTime(recording.duration)}</div>
                </div>
                <div class="history-actions">
                    <button class="history-btn btn-play" data-id="${recording.id}">▶️</button>
                    <button class="history-btn btn-delete" data-id="${recording.id}">🗑️</button>
                </div>
            </div>
        `).join("") :
        `<div class="no-history">暂无朗读记录</div>`;
}

// 播放录音
function playRecording(id) {
    const recording = gameState.recordings.find(r => r.id === id);
    if (recording) {
        elements.audioPlayer.src = recording.url;
        elements.audioPlayer.classList.remove("hidden");
        elements.audioPlayer.play();
    }
}

// 确认删除录音
function confirmDeleteRecording(id) {
    if (confirm("确定要删除这条录音吗？")) {
        deleteRecording(id);
    }
}

// 删除录音
function deleteRecording(id) {
    const index = gameState.recordings.findIndex(r => r.id === id);
    if (index !== -1) {
        // 释放对象URL
        URL.revokeObjectURL(gameState.recordings[index].url);

        // 从数组中移除
        gameState.recordings.splice(index, 1);

        // 保存并更新UI
        saveGameData();
        renderHistoryList();
        showToast("录音已删除");
    }
}

// 确认删除所有录音
function confirmDeleteAll() {
    if (gameState.recordings.length === 0) return;

    if (confirm("确定要删除所有录音记录吗？此操作不可撤销！")) {
        // 释放所有对象URL
        gameState.recordings.forEach(recording => {
            URL.revokeObjectURL(recording.url);
        });

        // 清空数组
        gameState.recordings = [];

        // 保存并更新UI
        saveGameData();
        renderHistoryList();
        showToast("所有录音已删除");
    }
}

// 格式化时间
function formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 格式化日期
function formatDate(isoString) {
    const date = new Date(isoString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-');
}

// 提示Toast
function showToast(message, duration = 3000) {
    const toast = document.createElement("div");
    toast.className = "toast";
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.classList.add("fade-out");
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

// 初始化游戏
window.addEventListener("DOMContentLoaded", initGame);